import itertools
from expression import Dot24Expression


brackets_ary_list = [
    ['(', None, None, ')', None, None, None, None],
    [None, None, None, None, '(', None, None, ')'],
    ['(', None, None, ')', '(', None, None, ')'],
    ['(', None, None, None, None, ')', None, None],
    ['((', None, None, ')', None, ')', None, None],
    ['(', None, '(', None, None, '))', None, None],
    [None, None, '(', None, None, None, None, ')'],
    [None, None, '(', None, None, None, None, ')'],
    [None, None, '(', None, None, None, None, ')'],
    [None, None, None, None, None, None, None, None],
]


def generate_operator_ary_list():
    operator_ary_list = []
    operators = ['+', '-', '*', '/']

    for i in range(len(operators)):
        for j in range(len(operators)):
            for k in range(len(operators)):
                operator_ary_list.append((operators[i], operators[j], operators[k]))

    return operator_ary_list


def generate_permutations(poker_list):
    permutations = list(itertools.permutations(poker_list, len(poker_list)))

    # print("所有可能的情况：", permutations)

    return permutations


def check_dot(poker_list):
    success_expression_list = []
    permutations = generate_permutations(poker_list)
    operator_ary_list = generate_operator_ary_list()

    for permutation in permutations:
        for operator_ary in operator_ary_list:
            for brackets_ary in brackets_ary_list:
                expression = Dot24Expression(poker_list=permutation,
                                             operator_list=operator_ary, brackets_list=brackets_ary)
                if expression.is_valid():
                    success_expression_list.append(expression)
                    print("成功表达式：", expression.expression1)

    print("成功表达式数量：", len(success_expression_list))

    return True


def main():
    count = 24
    for i in range(0, count):

        try:
            user_input = input("请输入一个由逗号分隔4张poker（例如：A,2,10,K）：")
            poker_list = user_input.split(',')
            poker_list = [poker.strip() for poker in poker_list]
            poker_list = [poker.upper() for poker in poker_list]

            # 检查输入是否合法
            if len(poker_list) != 4:
                print("输入poker数量不合法，请重新输入！")
                continue

            for poker in poker_list:

                if poker not in ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']:
                    print("输入poker不合法，请重新输入！")
                    continue

            check_dot(poker_list)

        except Exception as e:
            print("输入poker不合法，请重新输入！")
            continue


if __name__ == '__main__':
    main()